/* eslint-disable no-mixed-operators */
/* eslint-disable no-array-constructor */
/* eslint-disable one-var */
import store from '@/store'
import router from '@/router'

const MSG = {
  CATCH_MSG: '网络异常，请检查网络',
  QUERY_ERR_MSG: '数据获取失败，请稍后重试',
  UPLOAD_ERR_MSG: '头像上传失败，请稍后重试',
  UPLOAD_EXCEED_SIZE: '上传头像图片大小不能超过500K',
  FILE_NAME_EXCEED_LENGTH: '文件名长度不能大于40个字符',
  FILE_EXCEED_SIZE: '上传文件大小不能超过200MB'
}

const QUERY = {
  PAGE_SIZE: 15,
  LOADING_TEXT: '数据加载中...',
  EMPTY_TEXT: '暂无数据'
}

let CONSTANTS = {
  DEFAULT_USER_TYPE: '2', // 普通用户
  DEFAULT_USER_STATE: '4', // 正常
  DEFAULT_USER_NATURE: '1', // 临时
  DEFAULT_USER_EFFECT_MON: '7776000000', // 三个月
  DEFAULT_ORG_STATE: '1', // 启用
  DEFAULT_PERS_SEX: '1', // 男
  USER_STATE_LOCK: '3', // 锁定
  USER_STATE_SLEEP: '2' // 休眠
}

let formatter = {
  /**
   * 格式化列表序号
   */
  formatIndex: function (index, currentPage, pageSize = QUERY.PAGE_SIZE) {
    if ((!index && index !== 0) || (!currentPage && currentPage !== 0)) {
      return ''
    }
    return index + (currentPage - 1) * pageSize + 1
  },

  /**
   * 格式化时间
   */
  formatDateTime: function (msec, formatter) {
    return msec ? new Date(msec).format(formatter || 'YYYY-MM-DD hh:mm') : ''
  },

  /**
   * 格式化密码
   */
  formatPwd: function (pwd) {
    return pwd ? '********' : ''
  },

  /**
   * 格式化表格列数据
   */
  formatTableCol: function (val, param) {
    let map = typeof param === 'string' ? store.state.dic.mapFormat[param] : param
    return map && (val || val === 0) ? map[val] : ''
  },

  /**
   * IP转成整型
   */
  IP2Int: function (ip) {
    let num = 0
    ip = ip.split('.')
    num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3])
    num = num >>> 0
    return num
  },

  /**
   * 整型解析为IP地址
   */
  int2IP: function (num) {
    num = num * 1
    let str, tt = new Array()
    tt[0] = (num >>> 24) >>> 0
    tt[1] = ((num << 8) >>> 24) >>> 0
    tt[2] = (num << 16) >>> 24
    tt[3] = (num << 24) >>> 24
    str = String(tt[0]) + '.' + String(tt[1]) + '.' + String(tt[2]) + '.' + String(tt[3])
    return str
  }
}

let filter = {
  /**
   * 过滤空格
   */
  filterSpace: function (params) {
    if (!params) {
      return params
    }
    if (typeof params === 'string') {
      return params.replace(/(^\s*)|(\s*$)/g, '')
    }
    let obj = JSON.parse(JSON.stringify(params))
    for (let key in obj) {
      obj[key] = typeof obj[key] === 'string' ? obj[key].replace(/(^\s*)|(\s*$)/g, '') : obj[key]
    }
    return obj
  },

  /**
   * 过滤非数字
   */
  filterNaN: function (input) {
    return input.replace(/[^\d]/g, '') * 1
  },

  /**
   * 过滤所有空格
   */
  allFilterSpace: function (obj) {
    for (const key in obj) {
      if (obj.hasOwnProperty(key) && obj[key]) {
        obj[key] = obj[key].replace(/\s+/g, '')
      }
    }
  }
}

let number = {
  /**
   * 加一个数，并返回字符串格式
   */
  addANum: function (val, num = 1, max = 10) {
    if (isNaN(Number(val)) || isNaN(Number(num))) {
      return ''
    }
    let res = val * 1 + num * 1
    if (max === isFinite || isNaN(Number(max))) {
      return res + ''
    }
    return res > max * 1 ? max + '' : res + ''
  }
}

let object = {
  /**
   * 清空对象的value值
   */
  clearValOfObj: function (obj) {
    if (!obj || obj === {}) return {}
    for (let key in obj) {
      typeof obj[key] === 'object' && Array.isArray(obj[key]) && (obj[key] = [])
      typeof obj[key] === 'object' && !Array.isArray(obj[key]) && obj[key] && (obj[key] = {})
      typeof obj[key] !== 'object' && (obj[key] = '')
    }
    return obj
  }
}

let array = {
  /**
   * 取某个字段拼接成字符串
   */
  jointValOfOneKey: function (list, key, mark = '、') {
    if (!list || !list.length) return ''
    let str = ''
    list.forEach((index, item) => {
      str += (index === 0 ? '' : mark) + item[key]
    })
    return str
  },

  /**
   * 取某个字段转换成list
   */
  selectOneKey: function (list, key) {
    if (!list || !list.length) return []
    return list.map(item => item[key])
  },

  /**
   * 通过value获取Key值
   */
  getKeyByValue: function (list, val, key = 'code', value = 'name') {
    if (!list || !list.length) return ''
    let res
    for (let item of list) {
      if (item[value] === val) {
        res = item[key]
        break
      }
    }
    return res
  },

  /**
   * 转化为el-tree树形结构数据
   */
  transToTreeData: function (arr) {
    let list = JSON.parse(JSON.stringify(arr))
    if (!list || !list.length) return []
    var map = {}
    for (var item of list) {
      map[item.id] = item
    }
    var nodes = []
    for (var lis of list) {
      var p = map[lis.pid]
      if (!p) {
        nodes.push(lis)
        continue
      }
      p.children || (p.children = [])
      p.children.push(lis)
    }
    return nodes
  },

  /*
    tree 去除无子节点的父节点
  */
  deletTree (tree, father, grand) {
    for (let node = tree.length - 1; node >= 0; node--) {
      if (tree[node].children.length === 0 && tree[node].type === 'mgroup') {
        tree.splice(node, 1)
        if (father && grand && father.children.length === 0) {
          this.deletTree(grand)
        }
      } else if (tree[node].children.length !== 0) {
        this.deletTree(tree[node].children, tree[node], tree)
      }
    }
    return nodes
  },

  /**
   * 树结构转化为扁平化结构
   */
  deepTraversal: function (tree) {
    let list = []
    tree.forEach(item => {
      const loop = data => {
        list.push(data)
        let children = data.children
        children && children.length && children.forEach(child => {
          loop(child)
        })
      }
      loop(item)
    })
    return list
  }
}

let upload = {
  /**
   * 判断上传头像图片大小是否超出限制
   */
  isLimited: function (size, limit = 500) {
    return size / 1024 <= limit
  }
}

let app = {
  /**
   * 关闭当前tab页
   */
  closeCurrTab: function (currPath, next) {
    let opts = store.state.app.options,
      index = opts.findIndex(item => item.path === currPath)
    store.commit('DEL_TAB', currPath)
    router.push(next || opts[index - 1])
  }
}

let pwdHandler = {
  // 密码验证规则的安全配置编码
  SAFE_CONFIG_CODE: 'PWD_CHECK_RULES',

  // 密码验证规则
  rules: [
    { label: '数字', reg: '[0-9]' },
    { label: '大写字母', reg: '[A-Z]' },
    { label: '小写字母', reg: '[a-z]' },
    { label: '特殊字符' }
  ],

  /**
   * 校验密码是否包含用户名
   */
  checkPwdByName (pwd, name) {
    if (pwd === name) {
      return '不能与用户名相同'
    }
    if (pwd.includes(name)) {
      return '不能包含用户名'
    }
    return ''
  },

  /**
   * 判断密码是否符合规则
   */
  checkPwdByRules (pwd, str = '0000') {
    let cbMsg = '', checked = true
    for (let i = 0; i < this.rules.length; i++) {
      if (str.charAt(i) !== '1') {
        continue
      }
      let rule = this.rules[i]
      cbMsg += ((!cbMsg ? '' : '、') + `${rule.label}`)
      if ((rule.reg && !new RegExp(rule.reg).test(pwd)) || (!rule.reg && !this.hasSpecial(pwd))) {
        checked = false
      }
    }
    return checked ? '' : cbMsg
  },

  /**
   * 判断字符串中是否包含特殊字符
   */
  hasSpecial (str) {
    for (var i in str) {
      var asc = str.charCodeAt(i)
      if (!(asc >= 48 && asc <= 57 || asc >= 65 && asc <= 90 || asc >= 97 && asc <= 122)) {
        return true
      }
    }
    return false
  },

  /**
   * 随机生成数字
   */
  getRandomInt: function (min, max) {
    min = Math.ceil(min)
    max = Math.floor(max)
    return Math.floor(Math.random() * (max - min + 1)) + min
  },

  /**
   * 随机生成符合全部规则的密码
   */
  getRandomPwd: function (len = 8) {
    len = len * 1
    len < 8 && (len = 8)
    len > 20 && (len = 20)
    let pwdArr = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz', '1234567890', '~!@#$%^&*_-+=?'],
      pwds = [],
      n = 0
    for (let i = 0; i < len; i++) {
      if (pwds.length < (len - 4)) {
        let itemIdx = Math.floor(Math.random() * 4)
        let pwdItem = pwdArr[itemIdx]
        let item = pwdItem[Math.floor(Math.random() * pwdItem.length)]
        pwds.push(item)
      } else {
        let newItem = pwdArr[n]
        let lastItem = newItem[Math.floor(Math.random() * newItem.length)]
        let spliceIdx = Math.floor(Math.random() * pwds.length)
        pwds.splice(spliceIdx, 0, lastItem)
        n++
      }
    }
    return pwds.join('')
  }
}

export default {
  MSG,
  QUERY,
  CONSTANTS,

  formatter,
  filter,
  number,
  object,
  array,
  upload,
  app,
  pwdHandler
}
